package com.example.springtest.file.service.impl;

import com.example.springtest.common.ServiceCode;
import com.example.springtest.common.ServiceException;
import com.example.springtest.file.mapper.FileMapper;
import com.example.springtest.file.pojo.File;
import com.example.springtest.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Override
    public void uploadFile(MultipartFile multipartFile, String name, String owner) {
        String fileName = saveFileToLocalServer(multipartFile);
        File file = new File();
        file.setName(name == null ? multipartFile.getOriginalFilename() : name);
        file.setOwner(owner);
        file.setPath("/uploads/" + fileName);
        int result = fileMapper.insert(file);
        if (result != 1) {
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "文件上传失败");
        }
    }

    private String saveFileToLocalServer(MultipartFile multipartFile) {
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            assert originalFilename != null;
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String targetFilename = UUID.randomUUID().toString().replace("-", "") + extension;

            Path targetDirectory = Paths.get(uploadDir + "/uploads/");
            if (!Files.exists(targetDirectory)) {
                Files.createDirectories(targetDirectory);
            }

            Path targetFile = targetDirectory.resolve(targetFilename);
            Files.write(targetFile, multipartFile.getBytes());

            return targetFilename;
        } catch (IOException e) {
            log.error("文件上传到本地服务器发生错误", e);
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "文件上传失败");
        }
    }

    public List<File> getFileList(){
        List<File> fileList=fileMapper.getList();
        if(fileList==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"不存在文件！");
        }
        return fileList;
    }
}